<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */

declare (strict_types=1);

namespace app\admin\controller;

use app\admin\BaseController;
use think\App;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\facade\Log;
use app\admin\model\Data as DataList;
use app\admin\model\DataConfig as DataConfigList;
use think\Paginator;

class Data extends BaseController
{
    private $school;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $session_admin = get_config('app.session_admin');
        $uid = Session::get($session_admin)['id'];

        $this->school = Db::name('admin')->where(['id' => $uid])->value("school");
    }

    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where[] = ['school', '=', $this->school];
            $where[] = ['status', '>=', 0];

            if (!empty($param['teacher'])) {
                $where[] = ['user', 'like', '%' . $param['teacher'] . '%'];
            }

            $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
            $data = DataList::where($where)
                ->order('addtime desc')
                ->paginate($rows, false, ['query' => $param]);

            return table_assign(0, '', $data);
        } else {
            return view();
        }
    }

    /**
     *  * @Notes: 添加记录
     *  * @Interface add
     * @return \json
     *  * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: Lichao
     *  * @Time: 2022/6/6   下午7:10
     */
    public function add()
    {
        $whereTypes[0] = ['status', '=', 1];
        $whereTypes[1] = ['school', '=', $this->school];

        $whereTypes[2] = ['type', '=', 'table'];
        $tableTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();

        $whereTypes[2] = ['type', '=', 'op'];
        $opTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();

        $whereTypes[2] = ['type', '=', 'paper'];
        $paperTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();
        View::assign(['table_types' => $tableTypes, 'op_types' => $opTypes, 'paper_types' => $paperTypes]);

        if (request()->isAjax()) {
            $param = get_params();
            if (!empty($param['id']) && $param['id'] > 0) {
                // 启动事务
                Db::startTrans();
                try {
                    $param['updatetime'] = time();
                    Db::name('Data')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            } else {
                // 启动事务
                Db::startTrans();
                try {
                    $form = [];
                    $formd = ['addtime' => time(), 'user' => $param['user'], 'kind' => $param['kind'], 'date' => $param['date'], 'school' => $this->school];

                    // 更新默认值
                    if (Db::name('data_default')->where(['name' => 'kind', 'school' => $this->school])->findOrEmpty()) {
                        Db::name('data_default')->where(['name' => 'kind', 'school' => $this->school])->update(['value' => $param['kind']]);
                        Db::name('data_default')->where(['name' => 'date', 'school' => $this->school])->update(['value' => $param['date']]);
                    } else {
                        Db::name('data_default')->insert(['name' => 'kind', 'school' => $this->school, 'value' => $param['kind']]);
                        Db::name('data_default')->insert(['name' => 'date', 'school' => $this->school, 'value' => $param['date']]);
                    }

                    foreach ($param as $index => $item) {
                        $ia = explode('-', $index);
                        if (count($ia) == 2) {
                            $form[$ia[1]][$ia[0]] = $item;
                        } else {
                            $form[0][$ia[0]] = $item;
                        }
                    }

                    foreach ($form as $i => $f) {
                        $nf = array_merge($f, $formd);
                        Db::name('Data')->strict(false)->field(true)->insertGetId($nf);
                    }

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            }
            return to_assign();
        } else {
            $id = empty(get_params('id')) ? 0 : get_params('id');
            if ($id > 0) {
                $record = Db::name('Data')->where(['id' => $id])->find();
                View::assign('record', $record);
            }

            $default = Db::name('data_default')->where(['school' => $this->school])->select();
            foreach ($default as $index => $item) {
                $map[$item['name']] = $item['value'];
            }

            if (!isset($map)) {
                $map['kind'] = '';
                $map['date'] = '';
            }

            View::assign('default', $map);
            View::assign('id', $id);
            return view();
        }
    }

    /**
     *  * @Notes: 查看详情
     *  * @Interface view
     *  * @author: Lichao
     *  * @Time: 2022/6/6   下午9:23
     */
    public function view()
    {
        $param = get_params();
        $name = $param["name"];

        $wherePrice[0] = ['status', '=', 1];
        $wherePrice[1] = ['school', '=', $this->school];

        $kind = Db::name("DataConfig")->where(['type' => 'table', 'name' => $param['kind'], 'status' => 1, 'school' => $this->school])->value("value");

        $date = $param['date'];
        $dates = explode('-', trim($date));
        $where[] = ['date', 'between', $dates];
        $where[] = ['status', '>=', 0];
        $where[] = ['school', '=', $this->school];
        $where[] = ['kind', '=', $kind];

        switch ($name) {
            case 'teacher':
                $data = DataList::where($where)->field('sum(amount) as amount,user,op,paper,`double`')
                    ->group('user,op,paper,double')
                    ->select();

                // 计算金额
                $userAmount = [];

                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->money = round(floatval($price) * floatval($v->amount), 2);

                    // 名字可能有空格
                    $v->user = trim($v->user);

                    if (array_key_exists($v->user, $userAmount)) {
                        $userAmount[$v->user]['money'] += $v->money;
                        $userAmount[$v->user]['money'] = round($userAmount[$v->user]['money'], 2);
                    } else {
                        $userAmount[$v->user]['money'] = round($v->money, 2);
                        $userAmount[$v->user]['name'] = $v->user;
                        $userAmount[$v->user]['ds'] = $dates[0];
                        $userAmount[$v->user]['de'] = $dates[1];
                    }
                }

                array_multisort(array_column($userAmount, 'money'), SORT_DESC, $userAmount);

                $result = [];
                foreach ($userAmount as $k => $v) {
                    $result[] = [$v['name'], $v['money']];
                }

                return json_encode($result);
            case 'summary':
                $data = DataList::where($where)->field('op,paper,`double`,sum(amount) as amount')
                    ->group('op,paper,double')
                    ->select();

                $sum = 0;

                // 计算金额
                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->money = round(floatval($price) * floatval($v->amount), 2);
                    $sum += $data[$k]->money;
                }

                $data[] = ['合计', '', '', '', '', $sum];
                return json_encode($data);
            case 'detail':
                $where[] = ['user', '=', $param['user']];

                $data = DataList::where($where)->order('date')->field('user,date,op,paper,`double`,content,amount')->select();

                $sum = 0;
                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->sum = round(floatval($price) * floatval($v->amount), 2);
                    $sum += $data[$k]->sum;
                }

                $data[] = ['合计', '', '', '', '', '', '', '', $sum];
                return json_encode($data);
        }
    }

    /**
     *  * @Notes: 删除记录
     *  * @Interface delete
     * @return \json
     *  * @throws \think\db\exception\DbException
     * @author: Lichao
     *  * @Time: 2022/6/6   下午9:23
     */
    public function delete()
    {
        $id = get_params("id");

        $data['status'] = '-1';
        $data['id'] = $id;
        $data['updatetime'] = time();
        if (Db::name('Data')->update($data) !== false) {
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }

    /**
     *  * @Notes: 报表查询
     *  * @Interface report
     *  * @author: Lichao
     *  * @Time: 2022/6/7   上午9:21
     */
    public function report()
    {
        $wherePrice[0] = ['status', '=', 1];
        $wherePrice[1] = ['school', '=', $this->school];

        if (request()->isAjax()) {
            $param = get_params();

            $date = $param['date'];
            $dates = explode('-', trim($date));
            $where[] = ['date', 'between', $dates];
            $where[] = ['status', '>=', 0];
            $where[] = ['school', '=', $this->school];

            $kind = Db::name("DataConfig")->where(['type' => 'table', 'name' => $param['kind'], 'status' => 1, 'school' => $this->school])->value("value");
            $where[] = ['kind', '=', $kind];

            if ($param['table'] == "teacher") {
                // $teacher = $param['teacher'];
                // if ($teacher) {
                // 	$where[] = ['user', '=', $teacher];
                // }

                $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
                $data = DataList::where($where)->field('sum(amount) as amount,user,op,paper,`double`')
                    ->group('user,op,paper,double')
                    ->select();

                // 计算金额
                $userAmount = [];

                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->money = round(floatval($price) * floatval($v->amount), 2);

                    // 名字可能有空格
                    $v->user = trim($v->user);

                    if (array_key_exists($v->user, $userAmount)) {
                        $userAmount[$v->user]['money'] += $v->money;
                        $userAmount[$v->user]['money'] = round($userAmount[$v->user]['money'], 2);
                    } else {
                        $userAmount[$v->user]['money'] = round($v->money, 2);
                        $userAmount[$v->user]['name'] = $v->user;
                        $userAmount[$v->user]['ds'] = $dates[0];
                        $userAmount[$v->user]['de'] = $dates[1];
                    }
                }

                array_multisort(array_column($userAmount, 'money'), SORT_DESC, $userAmount);

                //分页配置信息
                $config = [
                    'var_page' => 'page',
                    'list_rows' => $rows,
                ];

                $page = isset($config['page']) ? (int)$config['page'] : Paginator::getCurrentPage($config['var_page']);
                $page = $page < 1 ? 1 : $page;
                $config['path'] = $config['path'] ?? Paginator::getCurrentPath();

                $total = count($userAmount);
                $result = Paginator::make(array_slice($userAmount, ($page - 1) * $rows, $rows), intval($rows), $page, $total, false, $config);

                return table_assign(0, '', $result);
            } elseif ($param['table'] == 'detail') {
                $where[] = ['user', '=', $param['user']];

                $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
                $data = DataList::where($where)->order('date')->paginate($rows, false, ['query' => $param]);

                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->sum = round(floatval($price) * floatval($v->amount), 2);
                }

                return table_assign(0, '', $data);
            } else {
                $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
                $data = DataList::where($where)->field('sum(amount) as amount,paper,op,`double`')
                    ->group('op,paper,double')
                    ->paginate($rows, false, ['query' => $param]);

                // 计算金额
                foreach ($data as $k => $v) {
                    $wherePrice[2] = ['op', '=', $v->op];
                    $wherePrice[3] = ['paper', '=', $v->paper];
                    $wherePrice[4] = ['double', '=', $v->double];
                    $price = Db::name('DataPrice')->where($wherePrice)->value('price');

                    $data[$k]->price = round($price, 2);
                    $data[$k]->money = round(floatval($price) * floatval($v->amount), 2);
                }

                return table_assign(0, '', $data);
            }
        } else {
            $detail = empty(get_params('detail')) ? 0 : get_params('detail');
            $date = empty(get_params('date')) ? 0 : get_params('date');
            $user = empty(get_params('user')) ? 0 : get_params('user');

            $kinds = Db::name('DataConfig')->where(['type' => 'table', 'status' => 1, 'school' => $this->school])->select()->toArray();
            $kind = empty(get_params('kind')) ? $kinds[0]['name'] : get_params('kind');

            View::assign('kinds', $kinds);
            View::assign('detail', $detail);
            View::assign('date', $date);
            View::assign('user', $user);
            View::assign('kind', $kind);

            return view();
        }
    }

    /**
     *  * @Notes: 配置页
     *  * @Interface config
     * @return \json|\think\response\View
     * @throws \think\db\exception\DbException
     *  * @author: Lichao
     *  * @Time: 2022/6/7   下午2:43
     */
    public function config()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where[] = ['status', '>=', 0];
            $where[] = ['school', '=', $this->school];

            $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
            $data = DataConfigList::where($where)->paginate($rows, false, ['query' => $param]);
            return table_assign(0, '', $data);
        } else {
            return view();
        }
    }

    /**
     *  * @Notes: 添加配置项
     *  * @Interface addConfig
     *  * @author: Lichao
     *  * @Time: 2022/6/7   下午2:45
     */
    public function add_config()
    {
        if (request()->isAjax()) {
            $param = get_params();
            if (!empty($param['id']) && $param['id'] > 0) {
                $exist = Db::name('DataConfig')->where(['type' => $param['type'], 'name' => $param['name'], 'status' => 1, 'school' => $this->school])->find();
                if ($exist) {
                    return to_assign(1, '字段已存在！');
                }

                Db::startTrans();
                try {
                    Db::name('DataConfig')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            } else {
                $exist = Db::name('DataConfig')->where(['type' => $param['type'], 'name' => $param['name'], 'status' => 1, 'school' => $this->school])->find();
                if ($exist) {
                    return to_assign(1, '字段已存在！');
                }

                Db::startTrans();
                try {
                    $maxId = Db::name('DataConfig')->where(['type' => $param['type'], 'status' => 1, 'school' => $this->school])->max('value');
                    if ($maxId === null) {
                        $param['value'] = 0;
                    } else {
                        $param['value'] = $maxId + 1;
                    }

                    $param['school'] = $this->school;
                    Db::name('DataConfig')->strict(false)->field(true)->insertGetId($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            }
            return to_assign();
        } else {
            $id = empty(get_params('id')) ? 0 : get_params('id');
            if ($id > 0) {
                $record = Db::name('DataConfig')->where(['id' => $id])->find();
                View::assign('record', $record);
            }
            View::assign('id', $id);
            return view();
        }
    }

    /**
     *  * @Notes: 删除配置项
     *  * @Interface delConfig
     *  * @author: Lichao
     *  * @Time: 2022/6/7   下午2:46
     */
    public function del_config()
    {
        $id = get_params("id");

        $data['status'] = '-1';
        $data['id'] = $id;
        if (Db::name('DataConfig')->update($data) !== false) {
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }

    /**
     *  * @Notes: 价格列表
     *  * @Interface price
     * @return \json|\think\response\View
     * @throws \think\db\exception\DbException
     *  * @author: Lichao
     *  * @Time: 2022/6/9   下午6:17
     */
    public function price()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where[] = ['status', '>=', 0];
            $where[] = ['school', '=', $this->school];

            $rows = empty($param['limit']) ? get_config('app . page_size') : $param['limit'];
            $data = Db::name('DataPrice')->where($where)->paginate($rows, false, ['query' => $param]);
            return table_assign(0, '', $data);
        } else {
            return view();
        }
    }

    /**
     *  * @Notes: 添加价格
     *  * @Interface add_price
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *  * @author: Lichao
     *  * @Time: 2022/6/9   下午6:17
     */
    public function add_price()
    {
        $whereTypes[0] = ['status', '=', 1];
        $whereTypes[1] = ['school', '=', $this->school];

        $whereTypes[2] = ['type', '=', 'table'];
        $tableTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();

        $whereTypes[2] = ['type', '=', 'op'];
        $opTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();

        $whereTypes[2] = ['type', '=', 'paper'];
        $paperTypes = Db::name('DataConfig')->where($whereTypes)->select()->toArray();
        View::assign(['table_types' => $tableTypes, 'op_types' => $opTypes, 'paper_types' => $paperTypes]);

        if (request()->isAjax()) {
            $param = get_params();
            if (!empty($param['id']) && $param['id'] > 0) {
                $exist = Db::name('DataPrice')->where(['op' => $param['op'], 'paper' => $param['paper'], 'double' => $param['double'], 'status' => 1, 'school' => $this->school])->find();
                if ($exist) {
                    return to_assign(1, '价格已存在！');
                }

                Db::startTrans();
                try {
                    Db::name('DataPrice')->where(['id' => $param['id']])->strict(false)->field(true)->update($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            } else {
                $exist = Db::name('DataPrice')->where(['op' => $param['op'], 'paper' => $param['paper'], 'double' => $param['double'], 'status' => 1, 'school' => $this->school])->find();
                if ($exist) {
                    return to_assign(1, '价格已存在！');
                }

                Db::startTrans();
                try {
                    $param['school'] = $this->school;
                    Db::name('DataPrice')->strict(false)->field(true)->insertGetId($param);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return to_assign(1, '提交失败:' . $e->getMessage());
                }
            }
            return to_assign();
        } else {
            $id = empty(get_params('id')) ? 0 : get_params('id');

            // 编辑
            if ($id > 0) {
                $record = Db::name('DataPrice')->where(['id' => $id])->find();
                View::assign('record', $record);
            }

            View::assign('id', $id);
            return view();
        }
    }

    /**
     *  * @Notes: 删除价格
     *  * @Interface del_price
     * @return \json
     * @throws \think\db\exception\DbException
     *  * @author: Lichao
     *  * @Time: 2022/6/9   下午6:16
     */
    public function del_price()
    {
        $id = get_params("id");

        $data['status'] = '-1';
        $data['id'] = $id;
        if (Db::name('DataPrice')->update($data) !== false) {
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }
}
